﻿using SuperJoe.Framework.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WWX.Admin.IDAL;
using WWX.Dto;
using WWX.Dto.Search;
using WWX.Model;
using SuperJoe.Framework.UnitOfWorkSql;
using SuperJoe.Framework.Core.Exceptions;

namespace WWX.Admin.BLL
{
    public class OrderBLL : BaseBLL<IOrderDAL>
    {
        public void Add(OrderAdminSaveDto dto)
        {
            var member = this.uow.ResolveDAL<IMemberDAL>().GetByAccount(dto.Account);
            if (member == null)
            {
                ThrowHelper.ThrowFriendlyException("账户不存在");
            }

            var order = new Order();
            order.MemberId = member.Id;
            order.No = NoHelper.GetNo("O");
            order.PurchasePrice = dto.PurchasePrice;
            order.SalePrice = dto.SalePrice;
            order.Remark = dto.Remark;
            order.LogisticsInfo = dto.LogisticsInfo;
            order.ProductInfo = dto.ProductInfo;
            order.Date = dto.Date;
            order.Status = dto.Status;
            order.Id = Guid.NewGuid().ToString();
            order.UpdatedBy = SuperJoeContext.Current.UserId;
            order.UpdatedTime = DateTime.Now;
            order.CreatedBy = SuperJoeContext.Current.UserId;
            order.CreatedTime = DateTime.Now;

            var memberDal = this.uow.ResolveDAL<IMemberDAL>();
            member = memberDal.Get(order.MemberId);

            Deal deal = new Deal();
            deal.Id = Guid.NewGuid().ToString();
            deal.CreatedBy = SuperJoeContext.Current.UserId;
            deal.CreatedTime = DateTime.Now;
            deal.ObjectType = DealObjectType.BuyProduct;
            deal.ObjectId = order.Id;
            deal.MemberId = order.MemberId;
            deal.No = NoHelper.GetNo("D");
            deal.AccountRemainCash = member.ZCash + member.Cash - order.SalePrice > 0 ? member.Cash + member.ZCash - order.SalePrice : 0;

            var salePrice = order.SalePrice;

            salePrice = salePrice - member.ZCash;

            if (salePrice == 0)//赠金刚好抵扣
            {
                order.IsDeducted = true;
                order.RemainPaymentMoney = 0;
                member.ZCash = 0;
                deal.Money = order.SalePrice;
            }
            else if (salePrice > 0)//赠金额度不够
            {
                member.ZCash = 0;
                member.Cash = member.Cash - salePrice;
                if (member.Cash < 0)//扣除余额还不够
                {
                    order.IsDeducted = false;
                    order.RemainPaymentMoney = -member.Cash;
                    deal.Money = order.SalePrice - order.RemainPaymentMoney;//交易金额等于订单金额-剩余扣款金额
                    member.Cash = 0;
                }
                else
                {
                    order.IsDeducted = true;
                    order.RemainPaymentMoney = 0;
                    deal.Money = order.SalePrice;
                }
            }
            else
            {
                member.ZCash = member.ZCash - order.SalePrice;
                deal.Money = order.SalePrice;
                order.IsDeducted = true;
                order.RemainPaymentMoney = 0;
            }


            this.uow.ExecuteInTran(() =>
            {
                memberDal.UpdateCash(member.Id, member.Cash, member.ZCash);
                this.dal.Add(order);
                this.uow.ResolveDAL<IDealDAL>().Add(deal);
            });

        }

        public Order Get(string id)
        {
            return this.dal.Get(id);
        }

        public void Update(OrderAdminSaveDto dto)
        {
            var order = this.Get(dto.Id);
            order.UpdatedBy = SuperJoeContext.Current.UserId;
            order.UpdatedTime = DateTime.Now;
            order.PurchasePrice = dto.PurchasePrice;
            order.SalePrice = dto.SalePrice;
            order.ProductInfo = dto.ProductInfo;
            order.Remark = dto.Remark;
            order.LogisticsInfo = dto.LogisticsInfo;
            order.Date = dto.Date;

            this.dal.Update(order);
        }

        public void UpdateStatus(string id, OrderStatus status)
        {
            var order = this.Get(id);
            order.Status = status;

            this.uow.ExecuteInTran(() =>
            {
                this.dal.Update(order);
            });

        }

        /// <summary>
        /// 扣款
        /// </summary>
        /// <param name="id"></param>
        public void DeductMoney(string id)
        {
            var order = this.Get(id);
            var deal = new Deal();
            deal.Id = Guid.NewGuid().ToString();
            deal.MemberId = order.MemberId;
            deal.ObjectId = order.Id;
            deal.ObjectType = DealObjectType.BuyProduct;
            deal.CreatedBy = SuperJoeContext.Current.UserId;
            deal.CreatedTime = DateTime.Now;
            deal.No = NoHelper.GetNo("D");

            var memberDal = this.uow.ResolveDAL<IMemberDAL>();
            var member = memberDal.Get(order.MemberId);
            if (member.Cash + member.ZCash < order.RemainPaymentMoney)
            {
                ThrowHelper.ThrowFriendlyException("用户余额不足，当前用户余额为：" + (member.Cash + member.ZCash));
            }
            else
            {
                deal.AccountRemainCash = member.Cash + member.ZCash - order.RemainPaymentMoney;
                var remainPaymentMoney = order.RemainPaymentMoney - member.ZCash;
                if (remainPaymentMoney == 0)//赠金中抵扣，刚好
                {
                    member.ZCash = 0;

                }
                else if (remainPaymentMoney > 0)//赠金额度不够
                {
                    member.ZCash = 0;
                    member.Cash = member.Cash - remainPaymentMoney;
                }
                else
                {
                    member.ZCash = member.ZCash - order.RemainPaymentMoney;
                }
            }

            deal.Money = order.RemainPaymentMoney;
            order.IsDeducted = true;
            order.RemainPaymentMoney = 0;
            

            this.uow.ExecuteInTran(() =>
            {
                memberDal.UpdateCash(member.Id, member.Cash, member.ZCash);
                this.dal.Update(order);
                this.uow.ResolveDAL<IDealDAL>().Add(deal);
            });
        }

        public List<OrderAdminDto> GetPageList(OrderAdminSearch search, int pageNo, int pageSize, out int total)
        {
            return this.dal.GetPageList(search, pageNo, pageSize, out total);
        }
    }
}
